<template>
    <div class="crm-receivable-container">
        <el-dialog title="修改回款信息" v-model="isShowDialog" :close-on-click-modal="false">
            <el-form ref="editCrmReceivableFormRef" :model="formData" :rules="formRules" label-width="120px">
                <el-row :gutter="35">
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="关联合同" prop="contractId">
                            <el-select v-model="formData.contractId" filterable remote 
                                @change="handContractChange"
                                @click="loadContractData()"
                                :remote-method="loadContractData" placeholder="请选择关联合同" clearable class="w100">
								<el-option 
									v-for="item in contracts"
									:key="item.id"
									:label="`（${item.contractCode}）${item.contractName}`"
									:value="item.id">
								</el-option>
							</el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="关联客户" prop="customerId">
                            <el-select v-model="formData.customerId"  placeholder="请选择关联客户" readonly class="w100">
								<el-option 
									v-for="item in customers"
									:key="item.id"
									:label="item.customerName"
									:value="item.id">
								</el-option>
							</el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="合同金额" prop="contractAmount">
                            <el-input-number v-model="formData.contractAmount" placeholder="合同金额（单位：元）" readonly class="w100"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="待收金额" prop="waitforAmount">
                            <el-input-number v-model="formData.waitforAmount" placeholder="待收金额（单位：元）" readonly class="w100"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="回款主题" prop="receivableName">
                            <el-input v-model="formData.receivableName" placeholder="请输入回款主题" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="回款日期" prop="paymentTime">
                            <el-date-picker v-model="formData.paymentTime" placeholder="请选择回款日期" value-format="YYYY-MM-DD" clearable class="w100"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="回款方式" prop="paymentMethod">
                            <Dictionary v-model="formData.paymentMethod" dict-label="crm_payment_method" placeholder="请选择回款方式"></Dictionary>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="回款金额" prop="paymentAmount">
                            <el-input-number v-model="formData.paymentAmount" :min="0" placeholder="请输入回款金额（单位：元）" clearable class="w100"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="备注" prop="remark">
                            <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="回款凭证" prop="attachments">
                            <Storage :model="attachment" @success="onUploadSuccess" @remove="onUploadRemove"></Storage>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="是否开票" prop="hasInvoice">
                            <el-switch v-model="formData.hasInvoice" active-text="是" inactive-text="否"></el-switch>
                        </el-form-item>
                    </el-col>
                    <!-- 开票信息 -->
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="发票类型" prop="invoiceType">
                            <Dictionary v-model="formData.invoice.invoiceType" dict-label="crm_invoice_type" placeholder="请输入发票类型"></Dictionary>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="抬头类型" prop="invoiceTitleType">
                            <Dictionary v-model="formData.invoice.invoiceTitleType" dict-label="crm_invoice_title" placeholder="请输入抬头类型"></Dictionary>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="开票抬头" prop="invoiceTitle">
                            <el-input v-model="formData.invoice.invoiceTitle" placeholder="请输入开票抬头" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="购方纳税识别号" prop="buyerTaxNumber">
                            <el-input v-model="formData.invoice.buyerTaxNumber" placeholder="请输入购方纳税识别号" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="购方开户行" prop="buyerDepositBank">
                            <el-input v-model="formData.invoice.buyerDepositBank" placeholder="请输入购方开户行" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="购方开户账户" prop="buyerDepositAccount">
                            <el-input v-model="formData.invoice.buyerDepositAccount" placeholder="请输入购方开户账户" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="购方开户地址" prop="buyerDepositAddress">
                            <el-input v-model="formData.invoice.buyerDepositAddress" placeholder="请输入购方开户地址" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="购方联系电话" prop="buyerTelephone">
                            <el-input v-model="formData.invoice.buyerTelephone" placeholder="请输入购方联系电话" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="receivables && receivables.length > 0">
                    <el-table :data="receivables" style="width: 100%" row-key="id">
                        <el-table-column type="index" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                        <el-table-column label="回款主题" prop="receivableName" show-overflow-tooltip></el-table-column>
                        <el-table-column label="客户名称" prop="customerName" show-overflow-tooltip></el-table-column>
                        <el-table-column label="回款日期" prop="paymentTime" show-overflow-tooltip></el-table-column>
                        <el-table-column label="回款方式" prop="paymentMethod" show-overflow-tooltip :formatter="loadPaymentMethod"></el-table-column>
                        <el-table-column label="回款金额" prop="paymentAmount" show-overflow-tooltip>
                            <template #default="scope">
                                <span>{{scope.row.paymentAmount}} 元</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="审核状态" prop="examineStatus" width="80" show-overflow-tooltip>
                            <template #default="scope">
                                <span v-if="scope.row.examineStatus == '0'" class="color-primary">草稿</span>
                                <span v-else-if="scope.row.examineStatus == '1'" class="color-warning">审核中</span>
                                <span v-else-if="scope.row.examineStatus == '2'" class="color-success">通过</span>
                                <span v-else-if="scope.row.examineStatus == '3'" class="color-danger">驳回</span>
                                <span v-else-if="scope.row.examineStatus == '4'" class="color-primary">撤回</span>
                                <span v-else-if="scope.row.examineStatus == '5'" class="color-info">作废</span>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="onCancel">取 消</el-button>
                    <el-button type="primary" @click="onSubmit">保 存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts">
import { reactive, toRefs, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { editCrmReceivable, getCrmReceivable } from '/@/api/crm/receivable/index';
import { getCrmContractList } from '/@/api/crm/contract/index';
import { getDictionaryByLabel } from '/@/api/system/dictionary/index';
import Dictionary from '/@/components/dictionary/index.vue';
import Storage from '/@/views/crm/components/storage/index.vue';
export default {
    name: 'crm/receivable/edit',
    components: { Dictionary, Storage },
    setup(props, context) {
        const editCrmReceivableFormRef = ref();
        const validAttachmentNotEmpty = (rule, value, callback) => {
            const { attachments } = state.formData;
            if(attachments == undefined || attachments.length == 0){
                return callback(new Error('回款凭证不能为空'));
            }else{
                return callback();
            }
        }
        const state = reactive({
            isShowDialog: false,
            contracts: [],
            customers: [],
            receivables: [],
            paymentMethods: [],
            attachment: {
                upload:{
                    limit: 5,
                    accept: '.jpg,.png,.svg,.webp,.gif,.pdf',
                    images: []
                }
            },
            formData: {
                attachments: [],
                hasInvoice: false,
                invoice: {
                    invoiceType: '',
                    invoiceTitleType: '',
                    invoiceTitle: '',
                    buyerTaxNumber: '',
                    buyerDepositBank: '',
                    buyerDepositAccount: '',
                    buyerDepositAddress: '',
                    buyerTelephone: '',
                },
            },
            formRules : {
                contractId: { required: true, message: '关联合同不能为空', trigger: 'blur' },
                customerId: { required: true, message: '关联客户不能为空', trigger: 'blur' },
                receivableName: { required: true, message: '回款主题不能为空', trigger: 'blur' },
                paymentTime: { required: true, message: '回款日期不能为空', trigger: 'blur' },
                paymentMethod: { required: true, message: '回款方式不能为空', trigger: 'blur' },
                paymentAmount: { required: true, message: '回款金额不能为空', trigger: 'blur' },
                attachments: { validator: validAttachmentNotEmpty, trigger: 'blur' },
            }
        });

        // 加载合同数据
        const loadContractData = (query?: string) => {
            if(query == '') return;
            getCrmContractList({contractCode: query, examineStatus: '2'}).then((res) => {
                if(res.code == 0){
                    state.contracts = res.data;
                }
            });
        };
        // 选择合同
        const handContractChange = (contractId) => {
            const contract = state.contracts.find(item => item.id == contractId);
            state.formData.contractId = contract?.id;
            state.formData.contractName = contract?.contractName;
            state.formData.contractAmount = contract?.contractAmount;
            state.formData.waitforAmount = contract?.awaitReceivable;
            state.customers = [{id: contract?.customerId, customerName: contract?.customerName}];
            state.formData.customerId = contract?.customerId;
            state.formData.customerName = contract?.customerName;
        };

        const loadPaymentMethod = (row, column, cellValue, index) => {
            return state.paymentMethods.find((item) => item.dictValue == cellValue)?.dictName;
        }

        const onUploadSuccess = (file, urls) => {
            state.formData?.attachments.push({url: file.url, name: file.name});
        };

        const onUploadRemove = (file, urls) => {
            const index = state.formData?.attachments.findIndex((item) => item.url == file.url);
            if(index > -1){
				state.formData?.attachments.splice(index, 1);
			}
        };

        // 打开弹窗
        const openDialog = (row?: object) => {
            state.isShowDialog = true;
            if(row){
                getCrmReceivable({id: row.id}).then((res) => {
                    if(res.code == 0){
                        const receivable = res.data;
                        state.formData = Object.assign({}, receivable);
                        state.formData.contractId = receivable?.contract?.id;
                        state.formData.contractName = receivable?.contract?.contractName;
                        state.formData.customerId = receivable.customerId;
                        state.formData.customerName = receivable.customerName;
                        state.formData.waitforAmount = receivable?.contract?.awaitReceivable;
                        state.formData.contractAmount = receivable?.contract?.contractAmount;
                        state.formData.invoice = receivable?.invoice || {};

                        state.contracts = [{id: receivable?.contract?.id, contractName: receivable?.contract?.contractName, contractCode: receivable?.contract?.contractCode}];
                        state.customers = [{id: receivable.customerId, customerName: receivable.customerName}];

                        state.attachment.upload.images = [];
                        if(state.formData.attachments){
							state.formData.attachments.forEach(item => state.attachment.upload.images.push({'url': item.url}));
						}
                    }
                });
            }else{
                state.formData = Object.assign({}, row);
                loadContractData('');
            }
            getDictionaryByLabel({ dictLabel: 'crm_payment_method' }).then((res: any) => {
                if (res.code == 0) {
                    state.paymentMethods = res.data;
                }
            });
        };
        // 关闭弹窗
        const closeDialog = (row?: object) => {
            state.isShowDialog = false;
            for(var key in state.formData) {
                state.formData[key] = undefined;
            }
            editCrmReceivableFormRef.value.resetFields();
            state.attachment.upload.images = [];
            state.formData. invoice = {
                invoiceType: '',
                invoiceTitleType: '',
                invoiceTitle: '',
                buyerTaxNumber: '',
                buyerDepositBank: '',
                buyerDepositAccount: '',
                buyerDepositAddress: '',
                buyerTelephone: '',
            };
        };
        // 取消
        const onCancel = () => {
            closeDialog();
        };
        // 新增
        const onSubmit = () => {
            editCrmReceivableFormRef.value.validate(valid => {
                if(valid){
                    let params = {
                        id: state.formData.id,
                        contractId: state.formData.contractId,
                        customerId: state.formData.customerId,
                        contractName: state.formData.contractName,
                        customerName: state.formData.customerName,
                        receivableName: state.formData.receivableName,
                        paymentTime: state.formData.paymentTime,
                        paymentMethod: state.formData.paymentMethod,
                        paymentAmount: state.formData.paymentAmount,
                        remark: state.formData.remark,
                        attachments: state.formData.attachments,
                        hasInvoice: state.formData.hasInvoice,
                    }
                    if(state.formData.hasInvoice){
                        params.invoice = state.formData.invoice;
                    }
                    editCrmReceivable(params).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('保存成功');
                            context.emit('submit');
                            closeDialog();
                        }
                    });
                }
            });
        };
        return {
            editCrmReceivableFormRef,
            openDialog,
            closeDialog,
            onCancel,
            onSubmit,
            loadContractData,
            handContractChange,
            loadPaymentMethod,
            onUploadSuccess,
            onUploadRemove,
            ...toRefs(state),
        };
    },
};
</script>